package cn.wit.summit.chwan.retrofit;

import android.content.Context;

import com.meituan.android.walle.WalleChannelReader;
import com.umeng.commonsdk.UMConfigure;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.wit.summit.chwan.models.request.AddPraiseRequest;
import cn.wit.summit.chwan.models.request.AllNetHotGameRequest;
import cn.wit.summit.chwan.models.request.CreateCommentRequest;
import cn.wit.summit.chwan.models.request.DailyNewRequest;
import cn.wit.summit.chwan.models.request.DeleteCommentRequest;
import cn.wit.summit.chwan.models.request.DiscoveryChoiceListRequest;
import cn.wit.summit.chwan.models.request.EditCommentRequest;
import cn.wit.summit.chwan.models.request.FollowGamesRequest;
import cn.wit.summit.chwan.models.request.GameDetialDataV2Request;
import cn.wit.summit.chwan.models.request.GameLibraryTwoLevelV3Request;
import cn.wit.summit.chwan.models.request.GameLibraryV3Request;
import cn.wit.summit.chwan.models.request.GamePlayTypeRequest;
import cn.wit.summit.chwan.models.request.GameRankingV3Request;
import cn.wit.summit.chwan.models.request.GetCommentDetailRequest;
import cn.wit.summit.chwan.models.request.GetCommentTokenRequest;
import cn.wit.summit.chwan.models.request.GetGameCommentRequest;
import cn.wit.summit.chwan.models.request.GreatCrackCollectionRequest;
import cn.wit.summit.chwan.models.request.MakeMoneyIndexV3Request;
import cn.wit.summit.chwan.models.request.MediaTestRequest;
import cn.wit.summit.chwan.models.request.PrizesGameListRequest;
import cn.wit.summit.chwan.models.request.SearchRequest;
import cn.wit.summit.chwan.models.request.ThematicListRequest;
import cn.wit.summit.chwan.models.request.TopicInfoRequest;
import cn.wit.summit.chwan.models.request.TopicListRequest;
import cn.wit.summit.chwan.models.request.TreviFountainRequest;
import cn.wit.summit.chwan.net.RpcConstant;
import cn.wit.summit.chwan.utils.AESUtils;
import cn.wit.summit.chwan.utils.GetPhoneAddressUtil;
import cn.wit.summit.chwan.utils.MD5Util;
import cn.wit.summit.chwan.utils.MetaUtils;
import cn.wit.summit.chwan.utils.StringToUnicodeUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.SystemInfoUtils;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Alan on 2018/6/4.
 */

public class RetrofitManager {

    private final int DEFAULT_TIMEOUT = 30;

    private static RetrofitManager retrofitManager;
    private        Retrofit        retrofit;
    private        Retrofit        retrofitComment;
    private        Retrofit        retrofitLogin;
    private        Retrofit        retrofitEnergy;

    private String adId;
    private String deviceId;
    private String umengId;
    private String version;
    private String token;
    private String mac;
    private String ip_address;
    private String channel_num;
    private String mobile_phone_model;
    private static String imei = "";
    private String access_token;

    private OkHttpClient.Builder client;
    private OkHttpClient.Builder clientLogin;

    public static RetrofitManager getInstance(Context context) {
        String imeiTemp = SystemInfoUtils.getInstance(context).getIMEI();
        if (retrofitManager == null || (!StringUtils.isEmpty(imeiTemp) && !imeiTemp.equals(imei))) {
            retrofitManager = new RetrofitManager(context);
        }
        return retrofitManager;
    }

    private RetrofitManager(Context context) {

        imei = SystemInfoUtils.getInstance(context).getIMEI();
        if (imei==null) imei="";
        deviceId = SystemInfoUtils.getInstance(context).getDeviceId();
        umengId = UMConfigure.getUMIDString(context);
        version = SystemInfoUtils.getInstance(context).getVersionName();

        String temp = creatRamNum(0) + '|' + version + '|' + creatRamNum(1)
                + '|' + deviceId + '|' + creatRamNum(3);
        access_token = AESUtils.keyEncrypt(temp);

        String md5String = deviceId + "gzRN53VWRF9BYUXo" + "mg2014";
        token = MD5Util.stringToMD5(md5String);
        channel_num = MetaUtils.getAd(context);
        mobile_phone_model = android.os.Build.MODEL;
        mac = GetPhoneAddressUtil.getAdresseMAC(context);
//        ip_address = GetPhoneAddressUtil.getNetIp();
        try {
            adId = WalleChannelReader.get(context, "adId");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(adId)) {
            adId = "0";
        }
        if (umengId == null || StringUtils.isEmpty(umengId)) {
            umengId = "null";
        }

        client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request request = original.newBuilder()
                        .header("Content-Type", "application/json; charset=UTF-8")
                        .header("version", version)
                        .header("device-id", deviceId)
                        .header("Unique-Code", umengId)
                        .header("access-token", access_token)
                        .header("imei", imei)
                        .header("adId", adId)
                        .header("ChaoHuiWan-App-Interal-Tags", "Salem501200")//请求标识
                        .method(original.method(), original.body())
                        .build();
                return chain.proceed(request);
            }
        });
        if (client != null) {
            client.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        }

        clientLogin = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request request = original.newBuilder()
                        .header("Content-Type", "application/x-www-form-urlencoded")
                        .header("version", version)
                        .header("device-id", deviceId)
                        .header("Unique-Code", umengId)
                        .header("access-token", access_token)
                        .header("imei", imei)
                        .header("adId", adId)
                        .header("ChaoHuiWan-App-Interal-Tags", "Salem501200")//请求标识
                        .method(original.method(), original.body())
                        .build();
                return chain.proceed(request);
            }
        });
        if (clientLogin != null) {
            clientLogin.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        }
    }

    private String creatRamNum(int m) {
        int num = (int) (Math.random() * 101);//0~100随机数
        return String.valueOf(num + (m * 100));
    }

    public Retrofit getRetrofit() {
        if (retrofit == null) {
            OkHttpClient httpClient = client.build();
            retrofit = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(RpcConstant.forumRootUrl)
                    .client(httpClient)
                    .build();
        }
        return retrofit;
    }

    public Retrofit getCommentRetrofit() {
        if (retrofitComment == null) {
            OkHttpClient httpClient = client.build();
            retrofitComment = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(RpcConstant.forumCommentRootUrl)
                    .client(httpClient)
                    .build();
        }
        return retrofitComment;
    }

    public Retrofit getLoginRetrofit() {
        if (retrofitLogin == null) {
            OkHttpClient httpClient = clientLogin.build();
            retrofitLogin = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(RpcConstant.forumLoginRootUrl)
                    .client(httpClient)
                    .build();
        }
        return retrofitLogin;
    }

    public Retrofit getEnergyRetrofit() {
        if (retrofitEnergy == null) {
            OkHttpClient httpClient = clientLogin.build();
            retrofitEnergy = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(RpcConstant.downEnnerGhy)
                    .client(httpClient)
                    .build();
        }
        return retrofitEnergy;
    }

    //游戏首发
    public DailyNewRequest getGameNewRequest(int pn, int pc) {
        return new DailyNewRequest(pn, pc);
    }

    //每日发现
    public DailyNewRequest getDailyDiscoverRequest(int pn, int pc) {
        return new DailyNewRequest(pn, pc);
    }

    //每日上新
    public DailyNewRequest getDailyNewRequest(int pn, int pc) {
        return new DailyNewRequest(pn, pc);
    }

    //获取点评token
    public GetCommentTokenRequest getCommentTokenRequest() {
        return new GetCommentTokenRequest(token, version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
    }

    //修改点评
    public EditCommentRequest editCommentRequest(String commentToken, String gameId, String uid, String userToken, String content, String comment_id, boolean isShow) {
        content = StringToUnicodeUtil.stringToUnicode(content);
        GetCommentTokenRequest te = new GetCommentTokenRequest(commentToken, version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new EditCommentRequest(te, gameId, uid, comment_id, userToken, content, creatRamNum(1), isShow ? "1" : "0");
    }

    //创建点评
    public CreateCommentRequest createCommentRequest(String commentToken, String gameId, String uid, String userToken, String head_portrait
            , String user_name, String content, boolean isShow) {
        return replayCommentRequest(commentToken, gameId, uid, userToken, head_portrait, user_name
                , content, "", "", ""
                , -1, "", -1, isShow);
    }

    //回复点评
    public CreateCommentRequest replayCommentRequest(String commentToken, String gameId, String uid, String userToken, String head_portrait, String user_name
            , String content, String reply_comment_id, String reply_comment_user_name, String reply_comment_user_id
            , int position, String details_comment_id, int pn, boolean isShow) {
        content = StringToUnicodeUtil.stringToUnicode(content);
        GetCommentTokenRequest te = new GetCommentTokenRequest(commentToken, version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        CreateCommentRequest temp = new CreateCommentRequest(te, gameId, uid, userToken, head_portrait, user_name
                , creatRamNum(1), content, reply_comment_id, reply_comment_user_name, reply_comment_user_id, position, details_comment_id
                , pn, isShow ? "1" : "0");
        return temp;
    }

    //删除评论
    public DeleteCommentRequest deleteCommentRequest(String commentToken, String gameId, int uid, String userToken, String comment_id, int pn) {
        GetCommentTokenRequest te   = new GetCommentTokenRequest(commentToken, version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        DeleteCommentRequest   temp = new DeleteCommentRequest(te, comment_id, gameId, uid, userToken, pn);
        return temp;
    }

    //点评详情
    public GetCommentDetailRequest getCommentDetailRequest(String commentToken, String gameId, String commentId, int uid, int pn, int pc, String sort) {
        GetCommentTokenRequest  te   = new GetCommentTokenRequest(commentToken, version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        GetCommentDetailRequest temp = new GetCommentDetailRequest(te, gameId, commentId, uid, pn, pc, sort);
        return temp;
    }

    //下载并安装
    public Map<String, String> getPlugRequest() {
        Map<String, String> tempMap = new HashMap<>();
        tempMap.put("uid", 0 + "");
        return tempMap;
    }

    //其他相关游戏
    public Map<String, String> getbackAllGameVersionRequest(String gameIds) {
        Map<String, String> tempMap = new HashMap<>();
        tempMap.put("package_name", gameIds);
        return tempMap;
    }

    //检查token并更新数据
    public Map<String, String> checkTokenRequest(int uid, String token) {
        Map<String, String> tempMap = new HashMap<>();
        tempMap.put("uid", uid + "");
        tempMap.put("token", token);
        return tempMap;
    }

    //回复点评
    public Map<String, String> getSurplusNumberRequest(int uid, String token) {
        Map<String, String> tempMap = new HashMap<>();
        tempMap.put("uid", uid + "");
        tempMap.put("token", token);
        return tempMap;
    }

    //许愿池
    public TreviFountainRequest sendTreviGamesRequest(String uid, String account, String token, String game_name, String game_info) {
        game_name = StringToUnicodeUtil.stringToUnicode(game_name);
        game_info = StringToUnicodeUtil.stringToUnicode(game_info);
        TreviFountainRequest mTreviFountainRequest = new TreviFountainRequest(uid, game_name, game_info, account, token);
        mTreviFountainRequest.setAccount(account);
        return mTreviFountainRequest;
    }

    //游戏详情点评列表
    public GetGameCommentRequest getGameCommentsRequest(String commentToken, String gameId, int uid, int pn, int pc) {
        GetCommentTokenRequest te = new GetCommentTokenRequest(commentToken, version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new GetGameCommentRequest(te, gameId, uid, pn, pc);
    }

    //点赞
    public AddPraiseRequest addPraiseRequest(String commentToken, String gameId, int uid, String userToken, String comment_id, int type, int pn) {
        GetCommentTokenRequest te = new GetCommentTokenRequest(commentToken, version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new AddPraiseRequest(te, gameId, uid, comment_id, userToken, type, pn);
    }

    //点踩
    public AddPraiseRequest unPraiseRequest(String commentToken, String gameId, int uid, String userToken, String comment_id, int type, int pn) {
        GetCommentTokenRequest te = new GetCommentTokenRequest(commentToken, version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new AddPraiseRequest(te, gameId, uid, comment_id, userToken, type, pn);
    }

    //详情点评
    public GetGameCommentRequest getGameDetailCommentRequest(String commentToken, String gameId, int uid) {
        GetCommentTokenRequest te   = new GetCommentTokenRequest(commentToken, version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        GetGameCommentRequest  temp = new GetGameCommentRequest(te, gameId, uid, 1, 20);
        return temp;
    }

    //游戏库首页
    public TopicListRequest getDiscoverIndexRequest(int pn, int pc) {
        return new TopicListRequest(0, pn, pc);
    }
    public DiscoveryChoiceListRequest getChoiceListRequest(int type, int sort_type, int tag_type, int game_type, int pn, int pc) {
        return new DiscoveryChoiceListRequest(type, sort_type, tag_type, game_type, pn, pc);
    }
    public TopicListRequest getTopicList(int belongTypeId, int pn, int pc) {
        return new TopicListRequest(belongTypeId, pn, pc);
    }

    public TopicInfoRequest getTopicInfo(String topic_id, int pn, int pc) {
        return new TopicInfoRequest(topic_id, pn, pc);
    }

    public DiscoveryChoiceListRequest getHotNewGameList(int type, int sort_type, int tag_type, int game_type, int pn, int pc) {
        if (type == 6)//google
        {
            return new DiscoveryChoiceListRequest(sort_type, tag_type, pn, pc);
        } else if (type == 5)//apple
        {
            return new DiscoveryChoiceListRequest(type, sort_type, tag_type, game_type, pn, pc);
        } else {
            return new DiscoveryChoiceListRequest(type, sort_type, tag_type, game_type, pn, pc);
        }
    }

    //游戏玩法
    public GamePlayTypeRequest gamePlayTypeRequest(int uid, int pn) {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new GamePlayTypeRequest(te, uid, pn);
    }

    //游戏库
    public GameLibraryV3Request gameLibraryV3Request(int uid, int pn) {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new GameLibraryV3Request(te, uid, pn);
    }

    //游戏库_二级页面-v3
    public GameLibraryTwoLevelV3Request gameLibraryTwoLevelV3Request(int pn, String typeId) {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new GameLibraryTwoLevelV3Request(te, pn, typeId);
    }

    //游戏库v3  type : 1网游榜  2单机榜
    public GameRankingV3Request gameRankingV3Request(int pn, int type) {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new GameRankingV3Request(te, pn, type);
    }

    //赚钱首页v3
    public MakeMoneyIndexV3Request makeMoneyIndexV3Request(int pn, String token) {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new MakeMoneyIndexV3Request(te, pn, token);
    }

    //全网最热游戏 syncType = 1    1:一起玩 2:应用宝 3:google 4:taptap
    public AllNetHotGameRequest allNetHotGameRequest(int syncType) {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new AllNetHotGameRequest(te, syncType);
    }

    //媒体评测
    public MediaTestRequest mediaTestRequest() {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new MediaTestRequest(te);
    }

    //了不起的破解集合
    public GreatCrackCollectionRequest greatCrackCollectionRequest(String collectionId, int pn) {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new GreatCrackCollectionRequest(te, collectionId, pn);
    }

    //奖项游戏列表
    public PrizesGameListRequest prizesGameListRequest(String prize_id, int pn, int pc) {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new PrizesGameListRequest(te, prize_id, pn, pc);
    }

    //收藏列表
    public FollowGamesRequest followGamesRequest(int uid, int pn, String token) {
        GetCommentTokenRequest te = new GetCommentTokenRequest(token, version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new FollowGamesRequest(te, uid, pn);
    }

    //游戏详情v2
    public GameDetialDataV2Request gameDetialDataV2Request(String game_id, int uid) {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new GameDetialDataV2Request(te, game_id, uid);
    }

    //专题列表
    public ThematicListRequest thematicListRequest(String merge_topic_id, int pn, int pc) {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new ThematicListRequest(te, merge_topic_id, pn, pc);
    }

    //搜索
    public SearchRequest searchRequest(String keyWorld, int pn, int tagId) {
        GetCommentTokenRequest te = new GetCommentTokenRequest("", version, deviceId, mac, ip_address, channel_num, mobile_phone_model);
        return new SearchRequest(te, keyWorld, pn, tagId);
    }
}
